const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);
const { Server } = require("socket.io");
var io = new Server(server, { cors: true });
const cors = require('cors')
app.use(cors())
let numbers = []
let numbers2 = []



let i = 0
io.on('connection', (socket) => {
    console.log('a user connected' + socket);
    socket.on('disconnect', function (data) {
        console.log('断开')
    })
    socket.on('message', function (data) {
        socket.broadcast.emit('message', data);    //将信息发给除自己以外的所有人
    })
    socket.on('hotZoneMessage', function (data) {
        var id = data.hotZoneName.slice(7, 8)
        numbers2 = numbers2.filter(item => {
            return item.id != id
        })
        numbers = numbers.filter(item => {
            return item != id
        })
        socket.broadcast.emit('hotZoneMessage', data)
    })
    // setInterval(() => {
    //     var n = randomNumber(0, 5);
    //     var value = numbers.indexOf(n);
    //     if (value == -1) {
    //         numbers.push(n)
    //         let x = randomNumber(-8, 8) * 5
    //         let z = randomNumber(-8, 8) * 5
    //         numbers2.push(id = n, randomObj = { x: x, z: z })
    //         let obj = {
    //             id: n,
    //             randomObj: {
    //                 x: x,
    //                 z: z  
    //             }
    //         }
    //         socket.emit('timingGoldCoinMessage', obj);
    //     }
    // }, 5000)
});


randomArr(6)

function randomArr(randomLength) {
    while (true) {
        var n = randomNumber(0, randomLength - 1);

        var value = numbers.indexOf(n);
        let x = randomNumber(-8, 8) * 5
        let z = randomNumber(-8, 8) * 5
        if (value == -1) {
            numbers.push(n);
            numbers2.push(id = n, randomObj = { x: x, z: z })
        }
        if (numbers.length == randomLength) break;
    }
}

app.get('/hotZone', (req, res) => {
    res.send(numbers2)
    console.log(numbers2);
})


function randomNumber(a = 0, b = 10) {
    var max = Math.max(a, b)
    var min = Math.min(a, b)
    if (isNaN(max)) throw "参数不规范";
    return Math.floor(Math.random() * (max - min + 1) + min)
}


//设置跨域访问
app.all('*', function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
    res.header('Access-Control-Allow-Headers', ['mytoken', 'Content-Type']);
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By", ' 3.2.1');
    // res.header("Content-Type", "application/json;charset=utf-8");
    res.header("Content-Type", 'charset=utf-8');
    next();
});

server.listen(3000, () => {
    console.log('listening on *:3000');
});
